import { pageListPriceRule, getPriceRuleById, updatePriceRule, deletePriceRule } from '@/services/rule/price_rule_api';
import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns, ProDescriptionsItemProps } from '@ant-design/pro-components';
import {
  FooterToolbar,
  ModalForm,
  PageContainer,
  ProDescriptions,
  ProFormText,
  ProFormTextArea,
  ProTable,
  TableDropdown
} from '@ant-design/pro-components';
import { FormattedMessage, useIntl } from '@umijs/max';
import { Button, Drawer, Input, message, Modal } from 'antd';
import React, { useRef, useState, useEffect } from 'react';
import { PageParams } from '../constants';
import AddForm from './components/AddForm';
import { PriceRuleVO } from "../constants"
import { set } from 'lodash';



const TableList: React.FC = () => {
     /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */
  const intl = useIntl();
  /**
   * @en-US Pop-up window of new window
   * @zh-CN 新建窗口的弹窗
   *  */  
  const [createModalOpen, handleModalOpen] = useState<boolean>(false);
  /**
   * @en-US The pop-up window of the distribution update window
   * @zh-CN 分布更新窗口的弹窗
   * */
  const [loading, setLoading] = useState(false);
  const [updateModalOpen, handleUpdateModalOpen] = useState<boolean>(false);

  const [showDetail, setShowDetail] = useState<boolean>(false);

  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<PriceRuleVO>();
  const [selectedRowsState, setSelectedRows] = useState<PriceRuleVO[]>([]);
  const [editRow, setEditRow] = useState<PriceRuleVO>();


  const getPriceRuleInfo = async (id: string) => {
    try {
      const response = await getPriceRuleById(id);
      if (response.code != 0) {
        if (!response.msg) {
          throw new Error(intl.formatMessage({ id: "request.error.create" }));
        } else {
          throw new Error(response.msg);
        }
      }
      setEditRow(response.data);
    } catch (error) {
      message.error(intl.formatMessage({ id: "request.error.retry" }));
      return false;
    }
  };

  const handleUpdatePriceRuleStatus = async (record: PriceRuleVO) => {
    try {
      const currentStatus = Number(record.status);
      const newStatus =      currentStatus === 0 || currentStatus === 1 ? currentStatus ^ 1 : 0;

      // 更新 status（如果需要）
      record.status = newStatus;
      const response = await updatePriceRule(record.id, record);
      if (response.code != 0) {
        if (!response.msg) {
          throw new Error(intl.formatMessage({ id: "request.error.create" }));
        } else {
          throw new Error(response.msg);
        }
      }
      if (actionRef.current) {
            actionRef.current.reload();
      }
    } catch (error) {
      message.error(intl.formatMessage({ id: "request.error.retry" }));
      return false;
    }
  };


  const queryPageData = async (pageParams: any) => {
    try {
      const response = await pageListPriceRule(pageParams);
      if (response.code != 0) {
        if (!response.msg) {
          throw new Error(intl.formatMessage({ id: "request.error.create" }));
        } else {
          message.error(response.msg);
        }
      }
      return response.data;
    } catch (error) {
      console.error(error);
      message.error(intl.formatMessage({ id: "request.error.retry" }));
    }
  };


  const pageQueryCustomer = async (params, sorter, filter) => {
    // 表单搜索项会从 params 传入，传递给后端接口。
    // console.log(params, sorter, filter);
    // const { current, pageSize, customerCode, customerName, customerStatus } = params
    
    return await queryPageData(params);
  }

  const makeActive = (record: PriceRuleVO) => {
    Modal.confirm({
      title: ( <FormattedMessage    id="pages.status.confirm.opt"    defaultMessage="Confirm Operate" /> ),
      content: (<FormattedMessage    id="pages.status.confirm.delete.record"   defaultMessage="Are you sure to delete this record?" /> ),
      okText:  ( <FormattedMessage    id="pages.button.confirm"    defaultMessage="Confirm" /> ),
      cancelText:  ( <FormattedMessage    id="pages.button.cancel"    defaultMessage="Cancel" /> ),
      onOk: async () => {
        const hide = message.loading('Processing...');
        try {
          // const status = record.customerStatus === 1 ? 0 : 1;
          const response = await deletePriceRule(record.id);
          if (response.code != 0) {
            if (!response.msg) {
              throw new Error(intl.formatMessage({ id: "request.error.create" }));
            } else {
              message.error(response.msg);
              return false;
            }
          }
          hide();
          message.success(intl.formatMessage({ id: "pages.status.delete.success",defaultMessage:'Delete Success'}));
          if (actionRef.current) {
            actionRef.current.reload();
          }
        } catch (error) {
          console.error(error);
          hide();
          message.error(intl.formatMessage({ id: 'request.error.retry' }));
        }
      },
    });
  }

 

  const columns: ProColumns<PriceRuleVO>[] = [
    {
      title: (
        <FormattedMessage
          id="pages.price.ruleName"
          defaultMessage="Rule Name"
        />
      ),
      dataIndex: "ruleName",
      key: "ruleName",
      sorter: true, // 允许排序
      search: {
        transform: (value) => value, // 可选：搜索转换逻辑
      },
    },
    {
      title: (
        <FormattedMessage
          id="pages.price.ruleCode"
          defaultMessage="Rule Code"
        />
      ),
      dataIndex: "ruleCode",
      key: "ruleCode",
      sorter: true,
      search: {
        transform: (value) => value,
      },
    },
    {
      title: (
        <FormattedMessage
          id="pages.price.ruleType"
          defaultMessage="Rule Type"
        />
      ),
      dataIndex: "ruleType",
      key: "ruleType",
      valueType: "select", // 下拉选择类型
      valueEnum: {
        '0': (
          <FormattedMessage
            id="pages.price.ruleType.base"
            defaultMessage="Base Fee"
          />
        ),
        '1': (
          <FormattedMessage
            id="pages.price.ruleType.special"
            defaultMessage="Special Fee"
          />
        ),
      },
      sorter: true,
      search: {
        transform: (value) => value,
      },
    },
    {
      title: (
        <FormattedMessage
          id="pages.price.feeItemCode"
          defaultMessage="Fee Item Code"
        />
      ),
      dataIndex: "feeItemCode",
      key: "feeItemCode",
      hideInTable: true, // 如果不需要在表格中显示（因为 ruleType=0 时可能为空）
      search: false
      // search: {
      //   transform: (value) => value,
      // },
    },
    {
      title: (
        <FormattedMessage
          id="pages.price.calculationRule"
          defaultMessage="Calculation Rule"
        />
      ),
      dataIndex: "calculationRule",
      key: "calculationRule",
      valueType: "select", // 下拉选择类型
      valueEnum: {
        Fixed_Price: (
          <FormattedMessage
            id="pages.price.calcType.fixedPrice"
            defaultMessage="Fixed Price"
          />
        ),
        Floating_Rate: (
          <FormattedMessage
            id="pages.price.calcType.floatingRate"
            defaultMessage="Floating Rate"
          />
        ),
        Fixed_Additional: (
          <FormattedMessage
            id="pages.price.calcType.fixedAdditional"
            defaultMessage="Fixed Additional"
          />
        ),
        Segmented: (
          <FormattedMessage
            id="pages.price.calcType.Segmented"
            defaultMessage="Segmented"
          />
        ),
      },
      sorter: true,
      search: {
        transform: (value) => value,
      },
    },
    {
      title: (
        <FormattedMessage
          id="pages.price.ruleValue"
          defaultMessage="Rule Value"
        />
      ),
      dataIndex: "ruleValue",
      key: "ruleValue",
      valueType: "digit", // 数字类型
      sorter: true,
      search: false,
    },
    {
      title: (
        <FormattedMessage
          id="pages.price.ruleExtendValue"
          defaultMessage="Extend Value"
        />
      ),
      dataIndex: "ruleExtendValue",
      key: "ruleExtendValue",
      sorter: true,
      search: false,
      width: 150, 
      ellipsis: true, 
    },
    {
      title: (
        <FormattedMessage id="pages.price.desc" defaultMessage="Rule Desc" />
      ),
      dataIndex: "description",
      key: "description",
      sorter: true,
      search: false,
      width: 150, 
      ellipsis: true, 
    },
    {
      title: (
        <FormattedMessage id="pages.price.status" defaultMessage="Status" />
      ),
      dataIndex: "status",
      key: "status",
      valueType: "select", // 下拉选择类型
      valueEnum: {
        '1': {
          text: (
            <FormattedMessage
              id="pages.status.disabled"
              defaultMessage="Disabled"
            />
          ),
          status: "error",
        },
        '0': {
          text: (
            <FormattedMessage
              id="pages.status.enabled"
              defaultMessage="Enabled"
            />
          ),
          status: "success",
        },
      },
      sorter: true,
      search: {
        transform: (value) => value,
      },
    },
    {
      title: (
        <FormattedMessage id="pages.operating" defaultMessage="Operating" />
      ),
      dataIndex: "option",
      valueType: "option",
      fixed: "right",
      width: 160,
      render: (_, record) => [
        <a
          key="edit"
          onClick={async () => {
            setCurrentRow(record);
            handleUpdateModalOpen(true); // 打开编辑弹窗
          }}
        >
          <FormattedMessage id="pages.edit" defaultMessage="Edit" />
        </a>,
        <a
          key="delete"
          onClick={() => {
            makeActive(record);
            setCurrentRow(record);
          }}
        >
          <FormattedMessage id="pages.delete" defaultMessage="Delete" />
        </a>,
        <TableDropdown
          key="actionGroup"
          onSelect={(key) => {
            if (key === "updateStatus") {
              // 手动触发重置密码逻辑
              handleUpdatePriceRuleStatus(record);
               
            }
            // 可以根据需要扩展其他菜单项的逻辑
          }}
          menus={[
            // { key: 'copy', name: '复制' },
            // { key: 'delete', name: '删除' },
            {
              key: "updateStatus",
              name:
                record.status === 0 ? (
                  <FormattedMessage
                    id="pages.status.disabled"
                    defaultMessage="Disabled"
                  />
                ) : (
                  <FormattedMessage
                    id="pages.status.enabled"
                    defaultMessage="Enabled"
                  />
                ),
            }, // 新增重置密码菜单项
          ]}
        />,
      ],
    },
  ];

  return (
    <PageContainer title={false}>
      <ProTable<PriceRuleVO, API.PageParams>
        headerTitle={intl.formatMessage({
          id: 'pages.price.list',
          defaultMessage: 'Price Rule List',
        })}
        actionRef={actionRef}
        loading={loading}
        rowKey="key"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              //新建
              handleModalOpen(true);
            }}
          >
            <PlusOutlined /> {" "}
            <FormattedMessage id="pages.price.create" defaultMessage="New" />
          </Button>,
        ]}
        request={pageQueryCustomer}
        columns={columns}
      />


      <AddForm
        // width="40%"
        visible={createModalOpen}
        // onOpenChange={handleModalOpen}
        onCancel={async () => { handleModalOpen(false) }}
        onSuccess={function (): void {
          handleModalOpen(false)
          setCurrentRow(undefined);
          if (actionRef.current) {
            actionRef.current.reload();
          }
        }}
      >
      </AddForm>

      <AddForm
        visible={updateModalOpen}
        values={currentRow}
        onCancel={async () => {
          handleUpdateModalOpen(false);
          setCurrentRow(undefined);
          setEditRow(undefined);
        }}
        onSuccess={function (): void {
          handleUpdateModalOpen(false)
          setCurrentRow(undefined);
          setEditRow(undefined);
          if (actionRef.current) {
            actionRef.current.reload();
          }
        }}
      >
      </AddForm>
    </PageContainer>
  );
};

export default TableList;
